<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-item :label="$t('columns.carCode')">
              <a-input :placeholder="$t('common.form.rule.input', {label: $t('columns.carCode')})" v-model="queryParam.carCode"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item :label="$t('columns.phone')">
              <a-input :placeholder="$t('common.form.rule.input', {label: $t('columns.phone')})" v-model="queryParam.phone"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item :label="$t('columns.plate')">
              <a-input :placeholder="$t('common.form.rule.input', {label: $t('columns.plate')})" v-model="queryParam.plate"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item :label="$t('columns.bindLicensePlate')">
              <a-checkbox v-model="queryParam.isBandingPlate">
                {{$t("dict.yesOrNo.1")}}
              </a-checkbox>
              <!-- <a-input placeholder="请输入绑定车牌" v-model="queryParam.isBandingPlate"></a-input> -->
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{ $t('common.table.query') }}</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">{{ $t('common.table.reset') }}</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">{{ $t('common.table.add') }}</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('租车车辆信息')">{{ $t('common.table.export') }}</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl"
        @change="handleImportExcel">
        <a-button type="primary" icon="import">{{ $t('common.table.import') }}</a-button>
      </a-upload>
      <!-- 高级查询区域 -->
      <j-super-query :fieldList="superFieldList" ref="superQueryModal"
        @handleSuperQuery="handleSuperQuery"></j-super-query>
      <!-- <a-button type="primary" @click="openControllerSettingsModal"
        :disabled="selectedRowKeys.length === 0">批量设置控制器</a-button> -->
      <a-button type="primary" @click="handleBatchQrcode" :disabled="selectedRowKeys.length === 0">{{ $t('btns.batchDownloadQrcode') }} </a-button>
      <!-- <j-modal title="控制器批量设置" :width="1000" :visible="controllerSettingsModalVisible"
        @cancel="controllerSettingsModalVisible = false" :mask="false">
        <ControllerBatchSettings :selectedCarIds="selectedRowKeys" @close="controllerSettingsModalVisible = false" />
      </j-modal> -->
      <!-- <a-button type="primary" @click="batchSetFence"
        :disabled="selectedRowKeys.length === 0">批量设置电子围栏</a-button> -->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />{{ $t('common.table.delete') }}</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> {{ $t('common.table.batchActions') }} <a-icon type="down" /></a-button>
      </a-dropdown>

      <a-button type="primary" @click="showIotTerminalTempList">{{ $t('btns.syncIot') }}</a-button>


    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> {{ $t('common.table.selected') }} <a style="font-weight: 600">{{
          selectedRowKeys.length }}</a>{{ $t('common.table.item') }}
        <a style="margin-left: 24px" @click="onClearSelected">{{ $t('common.table.empty') }}</a>
      </div>

      <a-table ref="table" size="middle" :scroll="{ x: true }" bordered rowKey="id" :columns="columns"
        :dataSource="dataSource" :pagination="ipagination" :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="fenceId" slot-scope="text, record, index">
          <a-button type="link" @click="handleFence(record)">
            {{  record.fenceName || '无围栏' }}
          </a-button>
        </template>

        <template slot="onlineStatus" slot-scope="text, record">
          <span v-if="text === 'offline'">
            <a-badge status="error" /> 离线
          </span>
          <span v-else-if="text === 'online'">
            <a-badge status="success" /> 在线
          </span>
          <span v-else>
            未知
          </span>
        </template>

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt=""
            style="max-width:80px;font-size: 12px;font-style: italic;" />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">{{ $t('common.table.edit') }}</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">{{ $t('common.table.more') }} <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">{{ $t('common.table.detail') }}</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="handleShowQrCode(record)">{{ $t("btns.viewQrcode") }}</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm :title="$t('confirmDelete')" @confirm="() => handleDelete(record.id)">
                  <a>{{ $t('common.table.delete') }}</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>

    <rental-car-modal ref="modalForm" @ok="modalFormOk"></rental-car-modal>

    <fence ref="fence" @submit="handleFenceSubmit"></fence>

    <a-modal v-model="qrCodeVisible" :title="$t('btns.qrcode')" @ok="handleOk">
      <QrCodeCard :qrValue="qrcodeData.qrValue" :qrTag="qrcodeData.qrTag"></QrCodeCard>
    </a-modal>

    <a-modal
      v-model="isModalVisible"
      width="80%"
      :title="$t('title')"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <IotTerminalTempList />
    </a-modal>
    <!--  -->
  </a-card>
</template>


<i18n>
  {
    "zh-CN": {
      "title": "终端上线临时管理",
      "columns": {
        "carTypeName": "车辆类型",
        "plate": "车牌编号",
        "customCode": "自编号",
        "carCode": "终端IMEI",
        "phone": "终端SN",
        "iccid": "iccidd",
        "frameCode": "车架编号",
        "emotorCode": "电机编号",
        "ctrlCode": "控制器编号",
        "dashboardCode": "仪表盘编号",
        "bmsCode": "电池编号",
        "manufacturerId": "制造商编码",
        "fenceId": "电子围栏",
        "onlineStatus": "在线状态",
        "bindLicensePlate": "绑定车牌"
      },
      "btns":{
        "viewQrcode":"查看二维码",
        "qrcode":"二维码",
        "downloadQrcode":"下载二维码",
        "batchDownloadQrcode":"批量下载二维码",
        "syncIot": "同步临时设备"
      },
      "dict":{
        "yesOrNo":{
          "1": "是",
          "0": "否"
        }
      }
    },
    "en-US": {
      "title": "Terminal Online Temporary Management",
      "columns": {
        "carTypeName": "Types of electric bicycles",
        "plate": "License plate number",
        "customCode": "Self Number",
        "carCode": "Terminal IMEI",
        "phone": "Terminal SN",
        "iccid": "iccidd",
        "frameCode": "Frame Number",
        "emotorCode": "Motor Number",
        "ctrlCode": "Controller Number",
        "dashboardCode": "Dashboard Number",
        "bmsCode": "Battery Number",
        "manufacturerId": "Manufacturer code",
        "fenceId": "Electronic Fence",
        "onlineStatus": "Presence",
        "bindLicensePlate": "Bind license plate"
      },
      "btns":{
        "viewQrcode":"View QR Code",
        "qrcode":"QR code",
        "downloadQrcode":"Download QR code",
        "batchDownloadQrcode":"Batch download QR codes",
        "syncIot": "Synchronize temporary devices"
      },
      "dict":{
        "yesOrNo":{
          "1": "YES",
          "0": "NO"
        }
      }
    },
    "fr-FR": {
      "title": "Gestion temporaire des terminaux en ligne",
      "columns": {
        "carTypeName": "Type de véhicule",
        "plate": "Numéro de plaque d'immatriculation",
        "customCode": "Auto - numéro",
        "carCode": "Terminal IMEI",
        "phone": "Terminal SN",
        "iccid": "iccidd",
        "frameCode": "Numéro de cadre",
        "emotorCode": "Numéro de moteur",
        "ctrlCode": "Numéro du Contrôleur",
        "dashboardCode": "Numéro du tableau de bord",
        "bmsCode": "Numéro de batterie",
        "manufacturerId": "Code du fabricant",
        "fenceId": "Clôture électronique",
        "onlineStatus": "Présence",
        "bindLicensePlate": "Plaque d'immatriculation liée"
      },
      "btns":{
        "viewQrcode":"Voir le Code QR",
        "qrcode":"Code 2D",
        "downloadQrcode":"Télécharger le Code QR",
        "batchDownloadQrcode":"Télécharger le Code QR par lot",
        "syncIot": "Synchronisation des équipements temporaires"
      },
      "dict":{
        "yesOrNo":{
          "1": "Oui",
          "0": "Non"
        }
      }
    }
  }
</i18n>

<script>

import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import RentalCarModal from './modules/RentalCarModal.vue'
import { getAction, postAction } from '@/api/manage'
import QrCodeCard from '@/components/qrcode/index.vue'
import ControllerBatchSettings from './modules/ControllerBatchSettings.vue';
import QRCode from 'qrcode'; // 确保你已经安装了qrcode库  
import JSZip from 'jszip';
import FileSaver from 'file-saver';
import Fence from '@/components/map/fence/Index.vue';

import IotTerminalTempList from './../iotTemp/IotTerminalTempList.vue'; // 替换为实际路径
export default {
  name: 'RentalCarList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    RentalCarModal,
    QrCodeCard,
    ControllerBatchSettings,
    Fence,
    IotTerminalTempList


  },
  data() {
    return {
      description: '租车车辆信息管理页面',
      controllerSettingsModalVisible: false, // 控制器设置弹窗可见性
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: this.$t('columns.carTypeName'),
          align: "center",
          dataIndex: 'carTypeName'
        },
        {
          title: this.$t('columns.plate'),
          align: "center",
          dataIndex: 'plate'
        },
        {
          title: this.$t('columns.customCode'),
          align: "center",
          dataIndex: 'customCode'
        }, 
        {
          title: this.$t('columns.carCode'),
          align: "center",
          dataIndex: 'carCode'
        },
        {
          title: this.$t('columns.phone'),
          align: "center",
          dataIndex: 'phone'
        },
        {
          title: this.$t('columns.iccid'),
          align: "center",
          dataIndex: 'iccid'
        },
        {
          title: this.$t('columns.frameCode'),
          align: "center",
          dataIndex: 'frameCode'
        },
        {
          title: this.$t('columns.emotorCode'),
          align: "center",
          dataIndex: 'emotorCode'
        },
        {
          title: this.$t('columns.ctrlCode'),
          align: "center",
          dataIndex: 'ctrlCode'
        },
        {
          title: this.$t('columns.dashboardCode'),
          align: "center",
          dataIndex: 'dashboardCode'
        },
        {
          title: this.$t('columns.bmsCode'),
          align: "center",
          dataIndex: 'bmsCode'
        },
        // {
        //   title: this.$t('columns.manufacturerId'),
        //   align: "center",
        //   dataIndex: 'manufacturerId'
        // }, 
        {
          title: this.$t('columns.fenceId'),
          align: "center",
          dataIndex: 'fenceId',
          scopedSlots: { customRender: 'fenceId' },
        }, 
        // {
        //   title: '终端类型',
        //   align: "center",
        //   dataIndex: 'terminalType'
        // }, {
        //   title: '终端编号',
        //   align: "center",
        //   dataIndex: 'terminalId'
        // },
        // {
        //   title:'蓝牙识别码',
        //   align:"center",
        //   dataIndex: 'blueCode'
        // },
        // {
        //   title:'蓝牙秘钥',
        //   align:"center",
        //   dataIndex: 'blueKey'
        // },
        {
          title: this.$t('columns.onlineStatus'),
          align: "center",
          dataIndex: 'onlineStatus',
          scopedSlots: { customRender: 'onlineStatus' }
        },
        {
          title: this.$t('common.table.actions'),
          dataIndex: 'action',
          align: "center",
          fixed: "right",
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: "/rental/ebike/list",
        setFence: "/rental/ebike/set-fence",
        delete: "/rental/ebike/delete",
        deleteBatch: "/rental/ebike/deleteBatch",
        exportXlsUrl: "/rental/ebike/exportXls",
        importExcelUrl: "/rental/ebike/importExcel",
        qrCodePrefixUrl: "/rental/config/vehicle-qrcode-prefix",
      },
      dictOptions: {},
      superFieldList: [],
      qrCodePrefix: "",
      qrCodeVisible: false,
      qrcodeData: {},
      isModalVisible: false,
    }
  },
  created() {
    this.getQrCodePrefix();
    this.getSuperFieldList();
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    },
  },
  methods: {
    /**
     * 显示电子围栏
     * @param record 
     */

    showIotTerminalTempList() {
      this.isModalVisible = true; // 显示弹出框
    },
    handleModalOk() {
      this.isModalVisible = false; // 处理确认
    },
    handleModalCancel() {
      this.isModalVisible = false; // 处理取消
    },
    handleFence(record){
      const result = this.$refs.fence.show(record.id,record.fenceId);
    },
    handleFenceSubmit(params){
      console.log("handleFenceSubmit--------:", params);
      this.loading = true;
      const { bizId, fenceId } = params;
      postAction(this.url.setFence, { id: bizId, fenceId: fenceId }).then(res => {
        if (res.success) {
          this.loadData();
          this.$message.success('设置电子围栏成功');
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    initDictConfig() {
    },
    "columns": {
        "plate": "车牌编号",
        "customCode": "自编号",
        "carCode": "终端IMEI",
        "phone": "终端SN",
        "iccid": "iccid",
        "frameCode": "车架编号",
        "emotorCode": "电机编号",
        "ctrlCode": "控制器编号",
        "dashboardCode": "仪表盘编号",
        "bmsCode": "电池编号",
        "manufacturerId": "制造商编码",
        "fenceId": "电子围栏",
        "onlineStatus": "在线状态",
        "bindLicensePlate": "绑定车牌"
      },
    getSuperFieldList() {
      let fieldList = [];
      fieldList.push({ type: 'string', value: 'plate', text: this.$t('columns.plate')})
      fieldList.push({ type: 'string', value: 'customCode', text: this.$t('columns.customCode')})
      fieldList.push({ type: 'string', value: 'carCode', text: this.$t('columns.carCode')})
      fieldList.push({ type: 'string', value: 'phone', text: this.$t('columns.phone')})
      fieldList.push({ type: 'string', value: 'iccid', text: this.$t('columns.iccid')})
      fieldList.push({ type: 'string', value: 'frameCode', text: this.$t('columns.frameCode')})
      fieldList.push({ type: 'string', value: 'emotorCode', text: this.$t('columns.emotorCode')})
      fieldList.push({ type: 'string', value: 'ctrlCode', text: this.$t('columns.ctrlCode')})
      fieldList.push({ type: 'string', value: 'dashboardCode', text: this.$t('columns.dashboardCode')})
      fieldList.push({ type: 'string', value: 'bmsCode', text: this.$t('columns.bmsCode')})
      this.superFieldList = fieldList
    },
    handleShowQrCode(record) {
      this.qrcodeData.qrValue = this.qrCodePrefix + "?code=" + record.code;
      this.qrcodeData.qrTag = record.plate;
      this.qrCodeVisible = true;
    },
    handleOk() {

    },
    openControllerSettingsModal() {
      if (this.selectedRowKeys.length > 0) {
        this.controllerSettingsModalVisible = true;
      } else {
        this.$message.warning('请选择至少一辆车进行控制器设置');
      }
    },
    getQrCodePrefix() {
      getAction(this.url.qrCodePrefixUrl, {}).then(res => {
        if (res.success) {
          this.qrCodePrefix = res.result.configValue;
        }
      })
    },
    async handleBatchQrcode() {
      let qrcodeList = [];
      for (let i = 0; i < this.selectedRowKeys.length; i++) {
        let record = this.selectionRows[i];
        const text = this.qrCodePrefix + "?code=" + record.code;
        const canvas = await this.createQrcode(text, record.plate);
        const blob = await this.canvasToBlob(canvas);
        qrcodeList.push({ name: record.plate, file: blob });
      }
      this.downloadAllQRCodes(qrcodeList);
    },
    canvasToBlob(canvas) {
      return new Promise((resolve, reject) => {
        try {
          canvas.toBlob(blob => {
            resolve(blob);
          });
        } catch (error) {
          reject(error);
        }
      });
    },
    qrCodeToCanvasPromise(canvas, text, options) {
      return new Promise((resolve, reject) => {
        QRCode.toCanvas(canvas, text, options, (error) => {
          if (error) {
            reject(error);
          } else {
            resolve();
          }
        });
      });
    },
    async createQrcode(text, name) {
      const canvas = document.createElement('canvas');
      // 生成二维码数据URL  
      await this.qrCodeToCanvasPromise(canvas, text, {});
      // 创建一个新的、更大的Canvas  
      const newCanvas = document.createElement('canvas');
      const newCtx = newCanvas.getContext('2d');
      newCanvas.width = canvas.width; // 假设宽度增加100  
      newCanvas.height = canvas.height + 50; // 假设高度增加50  

      // 将原始Canvas的内容绘制到新的Canvas上  
      newCtx.drawImage(canvas, 0, 0, canvas.width, canvas.height);

      // const qrCodeSize = 200;
      const textSize = 16;
      // const padding = 10;
      // canvas.width = qrCodeSize + padding * 2;
      // canvas.height = qrCodeSize + textSize + padding * 2;
      newCtx.font = `${textSize}px Arial`;
      newCtx.fillStyle = 'black';
      newCtx.textAlign = 'center';
      newCtx.textBaseline = 'middle';
      newCtx.fillText(name, newCanvas.width / 2, newCanvas.height - 30);
      console.log(newCanvas);
      return newCanvas;
    },
    downloadAllQRCodes(images) {
      const zip = new JSZip();
      console.log("downloadAllQRCodes---------------:", images);
      images.forEach((img) => {
        console.log("img:", img.file);
        zip.file(`${img.name}.png`, img.file, { binary: true });
      });
      // 生成并下载zip文件  
      zip.generateAsync({ type: 'blob' }).then((content) => {
        console.log("content:", content);
        FileSaver.saveAs(content, 'qrcode.zip');
      });
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>